package com.zzw.springboot.controller;

import com.zzw.springboot.config.RabbitMQConfig;
import com.zzw.springboot.service.RabbitMQService;
import com.zzw.springboot.util.Result;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * RabbitMQ测试控制器
 */
@RestController
@RequestMapping("/rabbitmq")
public class RabbitMQController {

    @Autowired
    private RabbitMQService rabbitMQService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息到RabbitMQ
     *
     * @param message 消息内容
     * @return 发送结果
     */
    @PostMapping("/send")
    public Result sendMessage(@RequestBody Map<String, Object> message) {
        if (rabbitMQService.sendMessage(message)) {
            return Result.success(200, "消息发送成功");
        } else {
            return Result.error(500, "消息发送失败");
        }
    }

    /**
     * 直接向队列发送消息（绕过消费者）
     *
     * @param res 消息内容
     * @return 结果
     */
    @GetMapping("/send-direct")
    public Result sendDirectMessage(@RequestParam String res) {
        try {
            Map<String, Object> message = new HashMap<>();
            message.put("id", UUID.randomUUID().toString());
            message.put("content", res);
            message.put("timestamp", System.currentTimeMillis());

            // 直接发送到队列，不经过交换机路由
            rabbitTemplate.convertAndSend("", RabbitMQConfig.QUEUE_NAME, message);

            return Result.success(200, "消息直接发送到队列成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "消息发送失败: " + e.getMessage());
        }
    }

    /**
     * 禁用消费者的方法（测试用）
     */
    @GetMapping("/disable-consumer")
    public Result disableConsumer() {
        try {
            // 创建一个新的测试队列，没有消费者监听
            String testQueueName = "test_queue_" + System.currentTimeMillis();
            rabbitTemplate.execute(channel -> {
                channel.queueDeclare(testQueueName, true, false, false, null);
                return null;
            });

            // 向测试队列发送10条测试消息
            for (int i = 0; i < 10; i++) {
                Map<String, Object> message = new HashMap<>();
                message.put("id", i);
                message.put("content", "测试消息-" + i);

                rabbitTemplate.convertAndSend("", testQueueName, message);
            }

            return Result.success(200, "创建测试队列并发送消息成功，队列名: " + testQueueName);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "测试失败: " + e.getMessage());
        }
    }
}
